import json
from dataclasses import dataclass, asdict
from http import HTTPStatus
from typing import Any, Optional

@dataclass
class ApiResponse:
    code: int
    message: str
    data: Optional[Any] = None

    def to_dict(self) -> dict:
        return asdict(self)
    
    def to_json(self) -> str:
        return json.dumps(self.to_dict(), ensure_ascii=False)

def success_response(
    data: Any = None, 
    message: str = "操作成功",
    code: int = HTTPStatus.OK
) -> ApiResponse:
    return ApiResponse(code=code, message=message, data=data)

def error_response(
    message: str = "操作失败",
    code: int = HTTPStatus.BAD_REQUEST,
    data: Any = None
) -> ApiResponse:
    return ApiResponse(code=code, message=message, data=data)